package com.zqs.compareface.utils.impl;


import org.opencv.core.*;
import org.opencv.highgui.HighGui;
import org.opencv.imgproc.Imgproc;
import org.opencv.objdetect.HOGDescriptor;
import org.opencv.videoio.VideoCapture;

/**
 * @version V1.0
 * @Title: OpenCVDetector.java
 * @Description:
 * @date: 2021年8月11日 21点27分
 */
public class HumanCheckUtil {
    static {
        // 在使用OpenCV前必须加载Core.NATIVE_LIBRARY_NAME类,否则会报错
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
    }

    public static void main(String[] args) {
        readCamera();
    }

    /**
     * 从视频文件获取视频
     * @Title: readVideo
     * @Description:
     * @param:
     * @date: 2021年8月11日 21点27分
     * @return: void
     */
    public static void readFileVideo(String path) {
        VideoCapture capture = new VideoCapture();
        capture.open(path);
        Mat image = new Mat();
        int index = 0;
        if (capture.isOpened()) {
            while (true) {
                capture.read(image);
                HighGui.imshow("行人检测", pedestrianDetection(image));
                index = HighGui.waitKey(1);
                if (index == 27) {// 需要按住退出键1s
                    System.exit(0);
                }
            }
        }
        capture.release();
    }

    /**
     * 从摄像头获取视频
     * @Title: readCamera
     * @Description:
     * @date: 2021年8月11日 21点27分
     * @return: void
     */
    public static void readCamera() {
        VideoCapture capture = new VideoCapture(0);
        Mat image = new Mat();
        int index = 0;
        if (capture.isOpened()) {
            while (true) {
                capture.read(image);
                HighGui.imshow("行人检测", pedestrianDetection(image));
                index = HighGui.waitKey(1);
                if (index == 27) {// 需要按住退出键1s
                    System.exit(0);
                }
            }
        }
        capture.release();
    }

    public static void readStream(){

    }
    /**
     * OpenCV-4.5.3 HOGDescriptor 自带行人检测
     *
     * @return
     * @return: void
     * @date: 2021年1月30日 23点27分
     */
    public static Mat pedestrianDetection(Mat src) {
        Mat gary = new Mat();
        Imgproc.cvtColor(src, gary, Imgproc.COLOR_BGR2GRAY);
        HOGDescriptor hog = new HOGDescriptor();
        hog.setSVMDetector(HOGDescriptor.getDefaultPeopleDetector());
        MatOfRect rect = new MatOfRect();
        hog.detectMultiScale(gary, rect, new MatOfDouble(), 0, new Size(4, 4), new Size(32, 32));
        Rect[] rects = rect.toArray();
        System.out.println("匹配到 "+rects.length+" 个人");
        for (int i = 0; i < rects.length; i++) {
            Imgproc.rectangle(src, new Point(rects[i].x, rects[i].y), new Point(rects[i].x + rects[i].width, rects[i].y + rects[i].height), new Scalar(0, 0, 255), 2, Imgproc.LINE_AA);
        }
        return src;
    }

}
